﻿using DotNetOpenAuth.AspNet;
using DotNetOpenAuth.AspNet.Clients;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace BoriPeter.NutritionManager.FatSecret
{
    public class FatSecretClient : OAuthClient
    {
        private string AccessToken;

        public static readonly ServiceProviderDescription FatSecretServiceDescription = new ServiceProviderDescription
        {
            RequestTokenEndpoint = new MessageReceivingEndpoint("http://www.fatsecret.com/oauth/request_token", HttpDeliveryMethods.GetRequest),
            UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://www.fatsecret.com/oauth/authorize", HttpDeliveryMethods.GetRequest),
            AccessTokenEndpoint = new MessageReceivingEndpoint("http://www.fatsecret.com/oauth/access_token", HttpDeliveryMethods.GetRequest),
            TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new PlaintextSigningBindingElement(), new HmacSha1SigningBindingElement(), }
        };

        public FatSecretClient(string consumerKey, string consumerSecret) : 
        this(consumerKey, consumerSecret, new AuthenticationOnlyCookieOAuthTokenManager())
        {
        }

        public FatSecretClient(string consumerKey, string consumerSecret, IOAuthTokenManager tokenManager) :
            base("FatSecret", FatSecretServiceDescription, new FatSecretTokenManager(consumerKey, consumerSecret, tokenManager))
        {
        }

        protected override AuthenticationResult VerifyAuthenticationCore(DotNetOpenAuth.OAuth.Messages.AuthorizedTokenResponse response)
        {
            AccessToken = response.AccessToken;
            return new AuthenticationResult(true, "FatSecret", response.AccessToken, "", null);
        }

        public override void RequestAuthentication(HttpContextBase context, Uri returnUrl)
        {
            base.RequestAuthentication(context, returnUrl);
        }
    }
}
